from flask import current_app, request, jsonify
from flask import render_template
from flask import session

from info import redis_store, constants
from info.models import User, News, Category
from info.utils.response_code import RET
from . import index_blu

@index_blu.route('/news_list')
def news_list():
    # 首页新闻列表
    # 获取参数
    # 新闻的分类id
    cid = request.args.get('cid', '10')
    page = request.args.get('page', '10')
    per_page = request.args.get('per_page', '10')
    # 校验参数
    try:
        page = int(page)
        cid = int(cid)
        per_page = int(per_page)
    except Exception as e:

        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数")

    filters = [News.status == 0]
    if cid != 1:
        # 添加条件
        filters.append(News.category_id == cid)

    try:
        paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page, per_page, False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询失败")
    # 取到当前也的数据
    news_model_list = paginate.items
    total_page = paginate.pages
    current_page = paginate.page

    news_dict_li = []
    for news in news_model_list:
        news_dict_li.append(news.to_basic_dict())

    data = {
        'total_page':total_page,
        'current_page':current_page,
        'news_dict_li':news_dict_li
    }

    return jsonify(errno=RET.OK, errmsg="ok111", data=data)

@index_blu.route('/')
def index():
    # 显示首页

    # 取到用户id
    user_id = session.get('user_id', None)
    user = None
    if user_id:
        # 尝试查询用户的模型
        try:
            user = User.query.get(user_id)
        except Exception as e:
            current_app.logger.error(e)
    # 右侧新闻
    news_list = []
    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)

    except Exception as e:
        current_app.logger.error(e)

    # 定义一个空的字典列表
    news_dict_li = []
    # 遍历对象列表，将对象的字典添加到字典列表中
    for news in news_list:
        news_dict_li.append(news.to_basic_dict())
    # 查询分类数据
    categories = Category.query.all()

    category_li = []
    for category in categories:
        category_li.append(category.to_dict())

    data = {
        'user': user.to_dict() if user else None,
        'news_dict_li':news_dict_li,
        'category_li':category_li
    }

    return render_template('news/index.html', data=data)

    # redis_store.set('name','itcats')
    # return render_template('news/index.html')

# 浏览器默认去找 根路径+ faviconico加载网页的图标
# send_static_file 是flask去查找指定的静态文件所调用的方法
@index_blu.route('/favicon.ico')
def favicon():
    return current_app.send_static_file('news/favicon.ico')


